import {post} from '../../../utils/axios'

const state = {
  name: '新增主机',
  type: {},
  dialog: false,
  terminal_time: null,
  emenu: false,
  re_per: {},
  status: {},
  fields: {},
  valid: null,
  hostnameRules: [
    (v) => !!v || '请输入主机名'
  ],
  ipRules: [
    (v) => !!v || '请输入IP'
  ],
  uuidRules: [
    (v) => !!v || '请输入UUID'
  ],
  typeRules: [
    (v) => !!v || '请输选择类型'
  ],
  msg: {
    uuid: '',
    ip: '',
    ilo_ip: '',
    vip: ''
  }
}

const mutations = {
  closeNewHost: (state, payload) => {
    state.dialog = false
  },
  saveHost (state, payload) {
    if (payload.validate()) {
      post('/hosts/',
        state.fields
      ).then((response) => {
        state.dialog = false
      }).catch((error) => {
        if (error.response.data) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
            console.log(state.msg)
          }
        }
      })
    }
  },
  newHostDialog (state, payload) {
    payload.reset()
    let msg = state.msg
    for (var i in msg) {
      msg[i] = ''
    }
  },
  loadHostSelect (state) {
    state.type = this._vm.$data.$$state.listhost.type
    state.re_per = this._vm.$data.$$state.listhost.re_per
    state.status = this._vm.$data.$$state.listhost.status
  }
}

const actions = {
  closeNewHost ({commit}) {
    commit('closeNewHost')
  },
  saveHost ({commit}, payload) {
    commit('saveHost', payload)
  },
  newHostDialog ({commit, state}, payload) {
    commit('newHostDialog', payload)
    if (!state.dialog) {
      this.dispatch('listhost/handlerHost')
    }
  },
  loadHostSelect ({commit}) {
    commit('loadHostSelect')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
